import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { MessageType, PostMessageType } from '@/config';
import { cn, generateRandomId, getDataUrl, getRandomElement, joinLink } from '@/lib/utils';
import { BackgroundReference, useSettingsStore } from '@/store';
import { Trash2 } from 'lucide-react';
import { useId } from 'react';
import { getIframeWindow } from './hook/useMeituxiuxiu';

// 提醒 dianxiaomi-meituxiuxiu-html 进行配置的刷新
async function processSettingUpdate() {
  const iframeWindow = await getIframeWindow();
  if (iframeWindow) {
    iframeWindow.postMessage(
      {
        type: PostMessageType.processSettingUpdate,
      },
      browser.runtime.getURL('/dianxiaomi-meituxiuxiu-html.html'),
    );
  }
}

export default function BaseDocSetting({
  className,
  ...props
}: {
  className: string;
} & React.HTMLAttributes<HTMLDivElement>) {
  const processSettings = useSettingsStore((state) => state.processSettings);
  const dispatch = useSettingsStore((state) => state.dispatch);
  const id = useId();
  // console.log(baseSettings);

  async function addBackgroundReference() {
    const fileHandles = await window.showOpenFilePicker({
      multiple: true,
      types: [
        {
          description: 'Images',
          accept: {
            'image/*': ['.png', '.jpg', '.jpeg'],
          },
        },
      ],
    });
    const backgroundReferenceList = await Promise.all(
      fileHandles.map(async (fileHandle) => {
        const file = await fileHandle.getFile();
        const dataUrl = await getDataUrl(file);
        return {
          id: generateRandomId(),
          dataUrl,
        };
      }),
    );
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.processSettings.backgroundReferenceList.push(...backgroundReferenceList);
        processSettingUpdate();
      },
    });
  }

  async function addSpliceBackgroundReference() {
    const fileHandles = await window.showOpenFilePicker({
      multiple: true,
      types: [
        {
          description: 'Images',
          accept: {
            'image/*': ['.png', '.jpg', '.jpeg'],
          },
        },
      ],
    });
    const spliceBackgroundReferenceList = await Promise.all(
      fileHandles.map(async (fileHandle) => {
        const file = await fileHandle.getFile();
        const dataUrl = await getDataUrl(file);
        return {
          id: generateRandomId(),
          dataUrl,
        };
      }),
    );
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.processSettings.spliceBackgroundReferenceList.push(
          ...spliceBackgroundReferenceList,
        );
        processSettingUpdate();
      },
    });
  }

  return (
    <div {...props} className={cn(className, 'flex flex-col')}>
      <div className="grow relative">
        <ScrollArea className="border !overflow-auto rounded-sm !absolute !h-full w-full pt-2 [&_[data-radix-scroll-area-viewport]]:absolute [&_[data-radix-scroll-area-viewport]]:!w-full">
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-1" htmlFor={id + '-generator-title-name'}>
              创建标题时设置的产品名称:
            </Label>
            <Input
              value={processSettings.generatorTitleName}
              placeholder="默认会使用顶级的目录名称"
              onChange={(event) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.generatorTitleName = event.target.value;
                  },
                });
              }}
              id={id + '-generator-title-name'}
              className="h-10 w-auto rounded-md border border-input px-3 py-2"
            />
            <Checkbox
              checked={processSettings.isUseAiGenerateTitle}
              onCheckedChange={(state) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.isUseAiGenerateTitle = state ? true : false;
                  },
                });
              }}
              id={id + '-is-use-ai-generate-title'}
              className="rounded-[2px] ml-3"
            />
            <Label
              className="whitespace-nowrap mb-0 ml-3"
              htmlFor={id + '-is-use-ai-generate-title'}
            >
              是否使用 ai 生成标题
            </Label>
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-1" htmlFor={id + '-allow-characters'}>
              标题额外允许的字符:
            </Label>
            <Input
              value={processSettings.allowCharacters}
              placeholder="设置标题除了[a-zA-Z0-9 ]允许的字符,使用 , 进行分隔"
              onChange={(event) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.allowCharacters = event.target.value;
                  },
                });
              }}
              id={id + '-allow-characters'}
              className="h-10 w-full rounded-md border border-input px-3 py-2"
            />
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-1" htmlFor={id + '-hot-search'}>
              热搜词:
            </Label>
            <Input
              value={processSettings.hotSearch}
              placeholder="热搜词会放置在生成标题的后面"
              onChange={(event) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.hotSearch = event.target.value;
                  },
                });
              }}
              id={id + '-hot-search'}
              className="h-10 w-[230px] rounded-md border border-input px-3 py-2"
            />
          </div>
          <div className="flex px-3 gap-2 items-center py-2">
            <Button
              onClick={async () => {
                const fileHandle = await window.showOpenFilePicker({
                  multiple: false,
                });
                const file = await fileHandle[0].getFile();
                const text = await file.text();
                const violateList = text.replace(/\r/g, '').split(/\n/);
                // console.log(violateList);
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.violateList = violateList;
                  },
                });
              }}
              size={'sm'}
              className="hover:bg-[#337AB7] bg-[#428BCA]"
            >
              添加为违禁词配置文件
              {processSettings.violateList &&
                processSettings.violateList.length > 0 &&
                `(已配置违禁词库)`}
            </Button>
            <div className="flex px-3 gap-2 py-4 items-center">
              <Checkbox
                checked={processSettings.isRemoveViolateList}
                onCheckedChange={(state) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.isRemoveViolateList = state ? true : false;
                    },
                  });
                }}
                id={id + '-is-remove-violate-list'}
                className="rounded-[2px]"
              />
              <Label className="whitespace-nowrap mb-0" htmlFor={id + '-is-remove-violate-list'}>
                遇到违禁词时是否删除违禁词后继续上传
              </Label>
            </div>
          </div>

          <div className="flex px-3 gap-2 items-center py-2">
            <Button
              onClick={async () => {
                const fileHandle = await window.showOpenFilePicker({
                  multiple: false,
                });
                const file = await fileHandle[0].getFile();
                const text = await file.text();
                const bannerWorldList = text.replace(/\r/g, '').split(/\n/);
                // console.log(violateList);
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.bannerWorldList = bannerWorldList;
                  },
                });
              }}
              size={'sm'}
              className="hover:bg-[#337AB7] bg-[#428BCA]"
            >
              添加为品牌词配置文件
              {processSettings.bannerWorldList &&
                processSettings.bannerWorldList.length > 0 &&
                `(已配置品牌词库)`}
            </Button>
            <div className="flex px-3 gap-2 py-4 items-center">
              <Checkbox
                checked={processSettings.isRemoveBannerWorldList}
                onCheckedChange={(state) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.isRemoveBannerWorldList = state ? true : false;
                    },
                  });
                }}
                id={id + '-is-remove-banner-world-list'}
                className="rounded-[2px]"
              />
              <Label
                className="whitespace-nowrap mb-0"
                htmlFor={id + '-is-remove-banner-world-list'}
              >
                遇到品牌词时是否删除品牌词后继续上传
              </Label>
            </div>
          </div>

          <div className="flex px-3 gap-2 py-4 items-center">
            <Checkbox
              checked={processSettings.isRemoveImageInProcess}
              onCheckedChange={(state) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.processSettings.isRemoveImageInProcess = state ? true : false;
                  },
                });
              }}
              id={id + 'is-remove-image-in-process'}
              className="rounded-[2px] mr-2"
            />
            <Label className="whitespace-nowrap mb-0" htmlFor={id + 'is-remove-image-in-process'}>
              是否在加工图片后保存图片到轮播图目录前删除轮播图中的图片
            </Label>
          </div>
          <div className="border border-input rounded-lg py-3 pl-2 relative !mt-6 mx-3">
            <span className="absolute left-5 top-0 translate-y-[-50%] px-1 text-base bg-white">
              场景图和白底图的加工设置
            </span>

            <div className="flex px-3 gap-2 py-4 items-center">
              <Checkbox
                checked={processSettings.isUseAiProcessScenceAndWhiteImages}
                onCheckedChange={(state) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.isUseAiProcessScenceAndWhiteImages = state
                        ? true
                        : false;
                    },
                  });
                }}
                id={id + 'is-use-ai-process-scence-and-white-images'}
                className="rounded-[2px] mr-2"
              />
              <Label
                className="whitespace-nowrap mb-0"
                htmlFor={id + 'is-use-ai-process-scence-and-white-images'}
              >
                是否对场景图和白底图进行 ai 加工
              </Label>

              <Checkbox
                checked={processSettings.isFilterProcessScenceAndWhiteImages}
                onCheckedChange={(state) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.isFilterProcessScenceAndWhiteImages = state
                        ? true
                        : false;
                    },
                  });
                }}
                id={id + 'is-filter-process-scence-and-white-images'}
                className="rounded-[2px] mr-2"
              />
              <Label
                className="whitespace-nowrap mb-0"
                htmlFor={id + 'is-filter-process-scence-and-white-images'}
              >
                是否对场景图和白底图进行滤镜处理
              </Label>
            </div>

            <div className="flex px-3 gap-2 items-center py-4">
              <Label className="whitespace-nowrap" htmlFor={id + '-comfy-UI-link'}>
                comfyUI的服务地址:
              </Label>
              <Input
                value={processSettings.comfyUILink}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.comfyUILink = event.target.value;
                    },
                  });
                }}
                id={id + '-comfy-UI-link'}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
            </div>

            <div className="flex px-3 gap-2 items-center py-4">
              <Label className="whitespace-nowrap" htmlFor={id + '-comfy-UI-files-link'}>
                comfyUI的生成目录地址:
              </Label>
              <Input
                value={processSettings.comfyUIFilesLink}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.comfyUIFilesLink = event.target.value;
                    },
                  });
                }}
                id={id + '-comfy-UI-files-link'}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
              <Button
                size={'sm'}
                onClick={() => {
                  window.open(joinLink(processSettings.comfyUIFilesLink, 'files/'));
                }}
              >
                查看AI生成图目录
              </Button>
            </div>

            <div className="flex px-3 gap-2 items-center py-4 flex-wrap">
              <Label className="whitespace-nowrap" htmlFor={id + '-comfy-UI-input-image-node-id'}>
                输入图像节点 ID:
              </Label>
              <Input
                value={processSettings.comfyUIInputImageNodeId}
                type="number"
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.comfyUIInputImageNodeId = +event.target.value;
                    },
                  });
                }}
                id={id + '-comfy-UI-input-image-node-id'}
                className="h-10 w-[100px] rounded-md border border-input px-3 py-2"
              />
              <Label
                className="whitespace-nowrap"
                htmlFor={id + '-comfy-UI-input-background-image-node-id'}
              >
                输入背景图像节点 ID:
              </Label>
              <Input
                value={processSettings.comfyUIInputBackgroundImageNodeId}
                type="number"
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.comfyUIInputBackgroundImageNodeId =
                        +event.target.value;
                    },
                  });
                }}
                id={id + '-comfy-UI-input-background-image-node-id'}
                className="h-10 w-[100px] rounded-md border border-input px-3 py-2"
              />
              <Label className="whitespace-nowrap" htmlFor={id + '-comfy-UI-output-image-node-id'}>
                输出图像节点 ID:
              </Label>
              <Input
                value={processSettings.comfyUIOutputImageNodeId}
                type="number"
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.comfyUIOutputImageNodeId = +event.target.value;
                    },
                  });
                }}
                id={id + '-comfy-UI-output-image-node-id'}
                className="h-10 w-[100px] rounded-md border border-input px-3 py-2"
              />
            </div>

            <div className="flex px-3 gap-2 items-center py-4">
              <Label className="whitespace-nowrap" htmlFor={id + '-ai-process-timeout'}>
                ai 图片加工的超时时间(秒):
              </Label>
              <Input
                value={processSettings.aiProcessTimeout}
                type="number"
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiProcessTimeout = +event.target.value;
                    },
                  });
                }}
                id={id + '-ai-process-timeout'}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
            </div>
            <div className="flex px-3 gap-2 items-center py-4">
              <Label className="whitespace-nowrap" htmlFor={id + '-ai-retry-time'}>
                ai 加工图片出错时的重试次数:
              </Label>
              <Input
                value={processSettings.aiRetryTime}
                type="number"
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiRetryTime = +event.target.value;
                    },
                  });
                }}
                id={id + '-ai-retry-time'}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
            </div>
            {/* <div className="flex px-3 gap-2 items-center py-4">
              <Label className="whitespace-nowrap">抠图后的尺寸比例:</Label>
              <Input
                type="number"
                value={processSettings.maskRatio.min}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.maskRatio.min = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
              <span>~</span>
              <Input
                type="number"
                value={processSettings.maskRatio.max}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.maskRatio.max = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
              />
            </div> */}
            <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray flex-wrap">
              <Label className="whitespace-nowrap mb-0">ai 生图时的背景参考:</Label>
              <Button
                onClick={addBackgroundReference}
                size="sm"
                className="ml-1 hover:bg-[#337AB7] bg-[#428BCA]"
              >
                添加背景参考
              </Button>
              <div className="flex basis-full items-center px-3 gap-2 mt-4"></div>
              {processSettings.backgroundReferenceList.map((item) => (
                <div
                  key={item.id}
                  className="relative w-[100px] h-[100px] rounded-md overflow-hidden group"
                >
                  <div
                    onClick={() => {
                      dispatch({
                        type: 'update',
                        update(draftState) {
                          draftState.processSettings.backgroundReferenceList =
                            draftState.processSettings.backgroundReferenceList.filter(
                              (backgroundReference) => backgroundReference.id !== item.id,
                            );
                          processSettingUpdate();
                        },
                      });
                    }}
                    className="absolute opacity-0 transition-opacity group-hover:opacity-100 top-1 right-1 text-destructive cursor-pointer"
                  >
                    <Trash2 size={16}></Trash2>
                  </div>
                  <img
                    onDoubleClick={(event) => {
                      const currentTarget = event.currentTarget;
                      currentTarget.requestFullscreen();
                    }}
                    src={item.dataUrl}
                    className="w-full h-full [&:fullscreen]:object-contain object-cover cursor-pointer"
                  />
                </div>
              ))}
            </div>
            {/* <div className="flex gap-2 items-center px-3 py-4 bd-bottom-gray">
              <Label className="whitespace-nowrap mb-0">生图倾向:</Label>
              <Input
                type="number"
                value={processSettings.aiTendency.min}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiTendency.min = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
              <span>~</span>
              <Input
                type="number"
                value={processSettings.aiTendency.max}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiTendency.max = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
              />
            </div>
            <div className="flex gap-2 items-center px-3 py-4">
              <Label className="whitespace-nowrap mb-0">创意相关性:</Label>
              <Input
                type="number"
                value={processSettings.aiCreative.min}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiCreative.min = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
              <span>~</span>
              <Input
                type="number"
                value={processSettings.aiCreative.max}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiCreative.max = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
              />
            </div>
            <div className="flex gap-2 items-center px-3 py-4">
              <Label className="whitespace-nowrap mb-0">采用步骤:</Label>
              <Input
                type="number"
                value={processSettings.aiSamplingStep.min}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiSamplingStep.min = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
              <span>~</span>
              <Input
                type="number"
                value={processSettings.aiSamplingStep.max}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.aiSamplingStep.max = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
              />
            </div> */}
          </div>

          <div className="border border-input rounded-lg py-3 pl-2 relative !mt-6 mx-3">
            <span className="absolute left-5 top-0 translate-y-[-50%] px-1 text-base bg-white">
              细节图加工设置
            </span>
            <div className="flex px-3 gap-2 py-4 items-center">
              <Checkbox
                checked={processSettings.isUseProcessSpliceImage}
                onCheckedChange={(state) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.isUseProcessSpliceImage = state ? true : false;
                    },
                  });
                }}
                id={id + 'is-use-process-splice-image'}
                className="rounded-[2px] mr-2"
              />
              <Label
                className="whitespace-nowrap mb-0"
                htmlFor={id + 'is-use-process-splice-image'}
              >
                是否对细节图行加工
              </Label>
            </div>
            <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray flex-wrap">
              <Label className="whitespace-nowrap mb-0">细节图拼接时的背景:</Label>
              <Button
                onClick={addSpliceBackgroundReference}
                size="sm"
                className="ml-1 hover:bg-[#337AB7] bg-[#428BCA]"
              >
                添加背景
              </Button>
              <div className="flex basis-full items-center px-3 gap-2"></div>
              {processSettings.spliceBackgroundReferenceList.map((item) => (
                <div
                  key={item.id}
                  className="relative w-[100px] h-[100px] rounded-md overflow-hidden group"
                >
                  <div
                    onClick={() => {
                      dispatch({
                        type: 'update',
                        update(draftState) {
                          draftState.processSettings.spliceBackgroundReferenceList =
                            draftState.processSettings.spliceBackgroundReferenceList.filter(
                              (backgroundReference) => backgroundReference.id !== item.id,
                            );
                          processSettingUpdate();
                        },
                      });
                    }}
                    className="absolute opacity-0 transition-opacity group-hover:opacity-100 top-1 right-1 text-destructive cursor-pointer"
                  >
                    <Trash2 size={16}></Trash2>
                  </div>
                  <img
                    onDoubleClick={(event) => {
                      const currentTarget = event.currentTarget;
                      currentTarget.requestFullscreen();
                    }}
                    src={item.dataUrl}
                    className="w-full h-full [&:fullscreen]:object-contain object-cover cursor-pointer"
                  />
                </div>
              ))}
            </div>
            <div className="flex gap-2 items-center px-3 py-4 bd-bottom-gray">
              <Label className="whitespace-nowrap mb-0" htmlFor={id + '-splice-margin'}>
                拼接时的外边框大小:
              </Label>
              <Input
                type="number"
                value={processSettings.spliceMargin}
                id={id + '-splice-margin'}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.spliceMargin = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
            </div>
            <div className="flex gap-2 items-center px-3 py-4">
              <Label className="whitespace-nowrap mb-0" htmlFor={id + '-splice-gap'}>
                拼接时的间距:
              </Label>
              <Input
                type="number"
                value={processSettings.spliceGap}
                id={id + '-splice-gap'}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.spliceGap = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
            </div>
            <div className="flex gap-2 items-center px-3 py-4">
              <Label className="whitespace-nowrap mb-0" htmlFor={id + '-splice-radiu'}>
                拼接时圆角:
              </Label>
              <Input
                type="number"
                value={processSettings.spliceRadiu}
                id={id + '-splice-radiu'}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.processSettings.spliceRadiu = +event.target.value;
                      processSettingUpdate();
                    },
                  });
                }}
                className="h-10 w-auto rounded-md border border-input px-3 py-2"
              />
            </div>
          </div>
        </ScrollArea>
      </div>
    </div>
  );
}
